package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

public class Flink05_KeyedState_ListState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //3.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorStream.keyBy("id");

        //4.针对每种传感器输出最高的3个水位值
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {

            //TODO 1.定义状态
            ListState<Integer> listState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //TODO 2.初始化状态
                listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("listState", Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<Tuple, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                //TODO 3.使用状态
                //1.将当前的水位直接保存到状态中
                listState.add(value.getVc());

                //2.再取出状态中的值
                Iterable<Integer> integers = listState.get();

                //3.为了方便做排序，将Iterable类型的数据放入list集合中
                ArrayList<Integer> top3List = new ArrayList<>();

                for (Integer integer : integers) {
                    top3List.add(integer);
                }

                //4.如果集合中的元素个数小于三个则不需要做排序，这三个水位就是最高的三个水位
                if (top3List.size()<=3){
                    out.collect(ctx.getCurrentKey()+"=>"+top3List.toString());
                }else {
                    //集合中的元素个数大于三，那么就需要先做排序然后取出前三个
                    top3List.sort(new Comparator<Integer>() {
                        @Override
                        public int compare(Integer o1, Integer o2) {
                            return o2-o1;
                        }
                    });

                    top3List.remove(3);
                    //更新状态
                    listState.update(top3List);
                    out.collect(ctx.getCurrentKey()+"=>"+top3List.toString());
                }

            }
        }).print();

        env.execute();
    }

}
